package com.majsubtense.main;

import com.majsubtense.core.InputStream;
import com.majsubtense.core.Notifier;
import com.majsubtense.core.components.UI;
import com.majsubtense.core.GameScene;
import com.majsubtense.core.events.*;
import com.majsubtense.main.gameScenes.Index;
import com.majsubtense.main.gameScenes.RaceVenue;

import java.util.ArrayList;
import java.util.List;

/**
 * @brief 游戏进程的主控制类，只负责游戏的运行逻辑
 */
public class GameController extends Notifier {
    private static final List<GameScene> gameScenes = new ArrayList<>();
    private static GameScene currentGameScene;

    public static void initialize() {
        UI.addListener(new EventHandler<>(
                GameSceneChangeEvent.ANY,
                gameSceneChangeEvent -> {
                    switch (gameSceneChangeEvent.getChangeTo()) {
                        case "Index" -> activateScene(Index.class);
                        case "RaceVenue" -> activateScene(RaceVenue.class);
                    }
                }
        ));

        gameScenes.add(new Index());
        gameScenes.add(new RaceVenue());
        // Set default game scene.
        activateScene(Index.class);
    }

    public static GameScene getCurrentGameScene() {
        return currentGameScene;
    }

    public static <T extends GameScene> GameScene getGameScene(Class<T> gameSceneClass) {
        for (GameScene scene : gameScenes)
            if (gameSceneClass.isAssignableFrom(scene.getClass()))
                return scene;
        return null;
    }

    public static <T extends GameScene> void activateScene(Class<T> gameSceneClass) {
        if (currentGameScene != null) {
            currentGameScene.setActive(false);
            currentGameScene.sceneStop();
        }
        GameScene gameScene = getGameScene(gameSceneClass);
        assert gameScene != null : "No game scenes are loaded!";
        currentGameScene = gameScene;
        currentGameScene.setActive(true);
        //////////////////////////////////////////
        InputStream.activateInput(gameScene); ////
        //////////////////////////////////////////
        SandboxApp.getStage().setScene(gameScene.getComponent(UI.ANY).getScene());
        gameScene.sceneStart();
    }
}
